package cn.kuick.match3.test4;

/**
 * 
 * @author 春凡
 * 
 *         4、字符串解码（Decode String） 给定一个编码的字符串，返回它的解码字符串。 （Given an encoded
 *         string, return it's decoded string.）
 *         编码规则：k[encoded_string]，表示在方括号内encoded_string被完全的重复k次。请注意，k保证是一个正整数。你可以假定输入字符串总是有效的；没有额外的空格，方括号也是配对出现的等等。
 *         （The encoding rule is: k[encoded_string], where the encoded_string
 *         inside the square brackets is being repeated exactly k times. Note
 *         that k is guaranteed to be a positive integer. You may assume that
 *         the input string is always valid; No extra white spaces, square
 *         brackets are well-formed, etc.）
 *         此外，你可以假定原始数据中不包含任何数字，数字只用于那些重复的数字k。例如：输入的内容中不会出现3a或2[4] （Furthermore,
 *         you may assume that the original data does not contain any digits and
 *         that digits are only for those repeat numbers, k. For example, there
 *         won't be input like 3a or 2[4].） 示例： s = "3[a]2[bc]"，返回："aaabcbc" s =
 *         "3[a2[c]]"，返回："accaccacc" s = "2[abc]3[cd]ef"，返回："abcabccdecdef"
 */
public class DecodeString_fan {

	public static void main(String[] args) {
//		decodeString("3[a2[c]]");
//		decodeString("2[abc]3[cd]ef");
//		decodeString("3[a]2[bc]"); 
//		decodeString("2[a3[bc]]fg2[e]");
		decodeString("10[a]2[bc]");
	}

	private static void decodeString(String source) {
		
		if(!source.contains("[")){
			System.out.println(source); 
			return;
		}
		
		// 数字字符串
		String numberString = "";
		
		int numberIndex = -1;
		int leftBraceIndex = 0;
		int rightBraceIndex = 0;
		for (int i = 0; i < source.length(); i++) {
			Character charA = source.charAt(i);

			if (isNumber(charA)) {
				if(leftBraceIndex>0){
					//如果前面有括号，又出现了数字，说明是嵌套的括号，需要把保存的数字串重新赋值，括号索引重置
					numberString = charA.toString();
					leftBraceIndex =0;
					numberIndex =i;
				}else{
					numberString += charA;
					if(numberIndex==-1){
						numberIndex =i;
					}
				}
				
			}else if("[".equals(charA.toString())){
				leftBraceIndex = i;
				
			}else if("]".equals(charA.toString())){
				rightBraceIndex = i;
				
				int number = Integer.parseInt(numberString);
				String string = source.substring(leftBraceIndex+1, rightBraceIndex); 
				String repeatString ="";
				for (int j = 0; j < number; j++) {
					repeatString+=string;
				}
				
				String newSource = source.substring(0, numberIndex).concat(repeatString).concat(source.substring(rightBraceIndex+1));
				decodeString(newSource);
				break;
			}
		}

	}

	private static boolean isNumber(Character c) {
		try {
			Integer.parseInt(c.toString());
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
}
